package com.css.fxfzdpzs.modules.xczh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdpzs.base.remote.RemoteService;
import com.css.fxfzdpzs.modules.xczh.dto.DisasterDamageDTO;
import com.css.fxfzdpzs.modules.xczh.entity.first.*;
import com.css.fxfzdpzs.modules.xczh.entity.second.*;
import com.css.fxfzdpzs.modules.xczh.externalEntity.EarEveManageInfoVo;
import com.css.fxfzdpzs.modules.xczh.repository.XczhRepository;
import com.css.fxfzdpzs.modules.xczh.service.XczhService;
import com.css.fxfzdpzs.modules.xczh.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class XczhServiceImpl implements XczhService {
    @Autowired
    XczhRepository xczhRepository;

    @Resource
    private RemoteService remoteService;

    private static final MathContext MC = new MathContext(10, RoundingMode.HALF_UP); // 设定精度和舍入模式

    @Override
    public GradeDisasterNum getDisasterNum() {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String jcsjUrl = configGroup.getProperty("jcsjRestUrl");
        GradeDisasterNum gradeDisasterNum = new GradeDisasterNum();
        //查询基础数据历史地震数量
        String url = jcsjUrl + "/datacenter/jcStrongCatalog/getDataList";
        JSONObject valueMap = new JSONObject();
        Object data = remoteService.getData(url, 3, valueMap).getData();
        if(data==null){
            gradeDisasterNum.setEarthquakeNum(0);
        }
        JSONArray jsonArray = (JSONArray) data;
        gradeDisasterNum.setEarthquakeNum(jsonArray.size());
        gradeDisasterNum.setDisasterNum(xczhRepository.getCount());
        return gradeDisasterNum;
    }

    @Override
    public List<DisasterNumVo> getDamageNum() {
        return xczhRepository.getDamageNum();
    }

    @Override
    public List<LossProportionVo> getLossProportion() {
        List<LossProportionVo> LossProportionList = new LinkedList<>();
        List<DisasterDamageData> lossList = xczhRepository.getLossProportion();
        if (CollectionUtils.isEmpty(lossList)){
            return Collections.emptyList();
        }
        lossList.forEach(item->{
            LossProportionVo lossProportionVo = new LossProportionVo();
            BigDecimal lossValue = item.getLossValue();
            lossProportionVo.setHouseLoss(getLossProportion(lossValue,item.getHouseLoss()));
            lossProportionVo.setRenovationLoss(getLossProportion(lossValue,item.getRenovationLoss()));
            lossProportionVo.setRoomLoss(getLossProportion(lossValue,item.getRoomLoss()));
            lossProportionVo.setLifelineLoss(getLossProportion(lossValue,item.getLifelineLoss()));
            lossProportionVo.setEnterprisesLoss(getLossProportion(lossValue,item.getEnterprisesLoss()));
            lossProportionVo.setDisasterLoss(getLossProportion(lossValue,item.getDisasterLoss()));
            lossProportionVo.setDistrict(item.getProvince()+item.getCounty());
            lossProportionVo.setMagnitude(item.getMagnitude().toString());
            LossProportionList.add(lossProportionVo);
        });

        return LossProportionList;
    }


    //计算损失占比
    private BigDecimal getLossProportion(BigDecimal totalLossValue,BigDecimal loss){
        BigDecimal lossProportion = BigDecimal.ZERO;
        lossProportion = totalLossValue.compareTo(BigDecimal.ZERO) != 0
                ? loss.divide(totalLossValue, 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100))
                : BigDecimal.ZERO;

        return lossProportion;
    }

    @Override
    public List<DisasterAssessData> getUnitCount() {
        return xczhRepository.getUnitCount();
    }

    @Override
    public List<DisasterValueVo> getDisasterValue() {
        return xczhRepository.getDisasterValue();
    }

    @Override
    public Map<String, Object> getVisitNum(String system,int num) {
        List<DisasterVisitsCount> list = xczhRepository.getVisitNum(system);
        List<DisasterVisitsCount> todayList = list.stream().sorted(Comparator.comparing(DisasterVisitsCount::getTodayVisitNum).reversed()).collect(Collectors.toList()).subList(0, Math.min(list.size(), num));
        List<DisasterVisitsCount> monthList = list.stream().sorted(Comparator.comparing(DisasterVisitsCount::getMonthVisitNum).reversed()).collect(Collectors.toList()).subList(0, Math.min(list.size(), num));
        List<DisasterVisitsCount> accumulateList = list.stream().sorted(Comparator.comparing(DisasterVisitsCount::getAccumulateVisitNum).reversed()).collect(Collectors.toList()).subList(0, Math.min(list.size(), num));
        Map<String, Object> map = new HashMap<>();
        map.put("todayList", todayList);
        map.put("monthList", monthList);
        map.put("accumulateList", accumulateList);
        int todaySum = list.stream().mapToInt(DisasterVisitsCount::getTodayVisitNum).sum();
        int accumulateSum = list.stream().mapToInt(DisasterVisitsCount::getAccumulateVisitNum).sum();
        map.put("todaySum", todaySum);
        map.put("accumulateSum", accumulateSum);
        return map;
    }

    @Override
    public List<DisasterDamage> getSituation() {
        return xczhRepository.getSituation();
    }

    @Override
    public List<XcDisasterImage> getDisasterImage(String iaId,String intensity) {
        List<XcDisasterImage> list = xczhRepository.getDisasterImage(iaId,intensity);
        return list;
    }

    @Override
    public XcDataNum getXcProportion(String iaId) {
        XcDataNum xcDataNum= xczhRepository.getXcProportion(iaId);
        String path = ClassUtils.getDefaultClassLoader()
                .getResource("").getPath() + "images" + File.separator + "34567123_20230817203910.jpg";
        String ss = path.substring(1, path.length());
        System.out.println(path);
        xcDataNum.setUrl(ss);
        return xcDataNum;
    }

    @Override
    public XcMapEntity getMapDate() {
        XcMapEntity xcMapEntity = new XcMapEntity();
        xcMapEntity.setId("6.8");
        xcMapEntity.setCounty("泸定县");
        xcMapEntity.setCountyCode("626100");
        xcMapEntity.setLongitude("102.21");
        xcMapEntity.setLatitude("29.90");
        xcMapEntity.setMagnitude("6.8");
        xcMapEntity.setOccurrenceTime("2023-01-12 12:52:00");
        List<XcMapEntityVO> list=new LinkedList<>();
        List<DisasterDamageVo> disasterDamageDataList =xczhRepository.getAllDisasterDamageData();
        DisasterDamageVo damageVo = xczhRepository.getMaxLossAndMinLoss();
        xcMapEntity.setMaxLoss(damageVo.getMaxLoss());
        xcMapEntity.setMinLoss(damageVo.getMinLoss());
        if (!CollectionUtils.isEmpty(disasterDamageDataList)){
            disasterDamageDataList.forEach(item->{
                String geom=xczhRepository.getGeomByLonAndLat(item.getLongitude(),item.getLatitude());
                XcMapEntityVO xcMapEntityVO=new XcMapEntityVO();
                xcMapEntityVO.setCounty(item.getCounty());
                xcMapEntityVO.setCountyCode(item.getCountyCode());
                xcMapEntityVO.setGeom(geom);
                xcMapEntityVO.setArea(item.getLossValue().toString());
                xcMapEntityVO.setLongitude(item.getLongitude());
                xcMapEntityVO.setLatitude(item.getLatitude());
                xcMapEntityVO.setMagnitude(item.getMagnitude());
                list.add(xcMapEntityVO);
            });

        }
        xcMapEntity.setList(list);


//        XcMapEntity entity= xczhRepository.getXcMapEntity();
//        List<XcMapEntityVO> list=xczhRepository.getCountySituation();
//        List<XcResultDate> resultDates=xczhRepository.getResultDates();
//        entity.setList(list);
//        entity.setResultDates(resultDates);
//        return entity;
        return xcMapEntity;
    }

    private String getArea(BigDecimal maxLoss, BigDecimal minLoss, BigDecimal lossValue) {
        if (maxLoss.compareTo(minLoss) <= 0) {
            throw new IllegalArgumentException("maxLoss must be greater than minLoss");
        }

        BigDecimal range = maxLoss.subtract(minLoss, MC);
        if (range.compareTo(BigDecimal.ZERO) == 0) {
            // 如果范围是0，那么直接返回0，因为任何值都映射到同一个点
            return BigDecimal.ZERO.toString();
        }

        BigDecimal scaledLoss = lossValue.subtract(minLoss, MC).divide(range, MC);
        // 确保结果在0到1之间
        scaledLoss = scaledLoss.max(BigDecimal.ZERO).min(BigDecimal.ONE);

        return scaledLoss.toString();

    }

    @Override
    public List<XcCountySituation> getCountyDisasterByCountyCode(String countyCode) {
        List<XcCountySituation> list= xczhRepository.getCountyDisasterByCountyCode(countyCode);
        return list;
    }

    @Override
    public XcSecondMapEntity getEarthquakeEventInfo(String longitude, String latitude, String magnitude, String eventTime) {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String xczhUrl = configGroup.getProperty("xczhRestUrl");

        longitude="121.640000";
        latitude="38.910000";
        magnitude="6.5";
        eventTime="2024-06-22 00:00:00";

        XcSecondMapEntity xcSecondMapEntity = new XcSecondMapEntity();

        //根据经纬度、震级、发震时间匹配对应地震事件
        String url = xczhUrl + "/largeScreen/getByCondition";
        url+= "?longitude="+longitude+
                "&latitude="+latitude+
                "&eventTime="+eventTime+
                "&magnitude="+magnitude+"";
        JSONObject valueMap = new JSONObject();
        Object data = remoteService.getData(url, 2, valueMap).getData();


        if(data==null){
            XcCountySituation disasterInfo= xczhRepository.getDisasterInfoByCondition(
                    new BigDecimal(longitude),new BigDecimal(latitude) );
            xcSecondMapEntity.setXcCountySituation(disasterInfo);
            return xcSecondMapEntity;
        }
        JSONObject jsonObject = (JSONObject) data;
        EarEveManageInfoVo earEveManage = JSON.parseObject(jsonObject.toJSONString(), EarEveManageInfoVo.class);
        List<XcResultDate>  resultDates =xczhRepository.getResultDatesByXsemId(earEveManage.getXsemId());
        xcSecondMapEntity.setResultDates(resultDates);
        xcSecondMapEntity.setXsemId(earEveManage.getXsemId());
//        xcSecondMapEntity.setLongitude("121.640000");
//        xcSecondMapEntity.setLatitude("38.920000");
//        xcSecondMapEntity.setCounty("南通县");
//        xcSecondMapEntity.setCountyCode("95525");
        return xcSecondMapEntity;
    }

    @Override
    public XcSecondMapEntity getSecondMapDate() {
        XcSecondMapEntity entity= xczhRepository.getSecondMapDate();
        List<XcResultDate> resultDates=xczhRepository.getResultDates();
        //entity.setResultDates(resultDates);
        return entity;
    }

    @Override
    public void xczhData() {

        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String xczhUrl = configGroup.getProperty("xczhRestUrl");

        //地震烈度图数据
        String url1 = xczhUrl + "/largeScreen/intensityMapData";
        JSONObject valueMap1 = new JSONObject();
        Object intensityMapData = remoteService.getData(url1, 3, valueMap1).getData();
        if(intensityMapData!=null){
            xczhRepository.delResultDate();
            JSONArray jsonArray1 = (JSONArray) intensityMapData;
            List<XcResultDate> intensityMaps = JSON.parseArray(jsonArray1.toJSONString(), XcResultDate.class);
            xczhRepository.saveXcResultDate(intensityMaps);
        }


        //现场数据占比
        String url2 = xczhUrl + "/largeScreen/getFieldDataProportion";
        JSONObject valueMap2 = new JSONObject();
        Object XcDataNumData = remoteService.getData(url2, 3, valueMap2).getData();
        if(XcDataNumData!=null){
            xczhRepository.delXcDataNum();
            JSONArray jsonArray2 = (JSONArray) XcDataNumData;
            List<XcDataNum> xcDataNums = JSON.parseArray(jsonArray2.toJSONString(), XcDataNum.class);
            xczhRepository.saveXcDataNum(xcDataNums);
        }


        //典型破坏照片
        String url3 = xczhUrl + "/largeScreen/getTypicalDamagePhoto";
        JSONObject valueMap3 = new JSONObject();
        Object photoData = remoteService.getData(url3, 3, valueMap3).getData();
        if(photoData!=null){
            xczhRepository.delDisasterImage();
            JSONArray jsonArray3 = (JSONArray) photoData;
            List<XcDisasterImage> xcDisasterImages = JSON.parseArray(jsonArray3.toJSONString(), XcDisasterImage.class);
            xczhRepository.saveDisasterImage(xcDisasterImages);
        }
    }
}
